package com.brayan.melinxa.logic.execution;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;

import javax.inject.Inject;
import javax.inject.Named;

import org.apache.log4j.Logger;

@Named
public class Delete implements Executable {

	Path eventObject, src = null, dest = null;
	@Inject
	private Logger logger;

	public Delete(Path fileObject, Path src, Path dest) {
		this.eventObject = fileObject;
		this.src = src;
		this.dest = dest;
	}

	public String getDestinationPath() {
		// TODO Auto-generated method stub
		return null;
	}

	public String getSourcePath() {
		// TODO Auto-generated method stub
		return null;
	}

	public void run() {
		String strObj = eventObject.toFile().getAbsolutePath();

		// d:\src\folder\ordner
		// cut the common prefix of the path
		// System.out.println(strObj);
		String src = this.src.toString();
		// System.out.println(src);
		String strDiff = strObj.replace((CharSequence) src, "");
		// System.out.println(strDiff);
		String copyDir = dest.toString() + strDiff;
		System.out.println("Deleting: " + copyDir);
		try {
			// If a delete event is signaled, then always recurisvely
			// delete the entire directory. Even if it's a rename.
			deleteSilently(new File(copyDir));
		} catch (IOException e) {
			//TODO use logger
			System.out.println("Failed to delete File/Directory. " + e.getMessage());
		}
	}

	void deleteSilently(File f) throws IOException {
		if (f.isDirectory()) {
			for (File c : f.listFiles())
				deleteSilently(c);
		}
		try {
			if (!f.delete()) {
				// TODO inject logger properly
				System.out.println("Failed to delete file/folder: " + f);
				// logger.info("Failed to delete file/folder: " + f);
			} else {
				// TODO fine grained logging
				System.out.println("Deleted " + f);
			}
		} catch (Exception ex) {
			// TODO inject logger properly
			System.out.println("Failed to delete file/folder: " + f);
			System.out.println(ex.getMessage());
			// logger.info("Failed to delete file/folder: " + f);
			// logger.info(ex.getMessage());
		}
		finally{
			//release the file. Allow garbage collector to grab file.
			f = null;
		}
	}

	public String getExecutableType() {		
		return "delete";
	}

}
